# -*- coding: utf-8 -*-
import sys
import os
import time
import win32gui
import win32con
import win32process
import subprocess
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, 
                           QMessageBox, QStackedWidget, QWidget, QVBoxLayout,
                           QLabel, QFrame,QHBoxLayout)
from PyQt5.QtCore import QThread,Qt, pyqtSignal
from PyQt5.QtGui import QFont

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("外部程序启动器")
        self.setFixedSize(900, 850)  # 固定窗口大小
        
        # 创建主布局
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QHBoxLayout(main_widget)
        
        # 左侧按钮区域 (200像素宽)
        button_frame = QFrame()
        button_frame.setFixedWidth(200)
        button_layout = QVBoxLayout(button_frame)
        
        # 创建立体感按钮
        self.button = self.create_3d_button("启动外部程序")
        self.button.clicked.connect(self.start_external_program)
        button_layout.addWidget(self.button)
        
        # 添加其他功能按钮
        self.button2 = self.create_3d_button("设置")
        self.button3 = self.create_3d_button("关于")
        button_layout.addWidget(self.button2)
        button_layout.addWidget(self.button3)
        button_layout.addStretch()
        
        # 右侧堆叠页面
        self.stacked_widget = QStackedWidget()
        
        # 添加页面1 - 主功能页
        page1 = QWidget()
        page1_layout = QVBoxLayout(page1)
        page1_layout.addWidget(QLabel("这里是主功能区域"))
        self.stacked_widget.addWidget(page1)
        
        # 添加页面2 - 设置页
        page2 = QWidget()
        page2_layout = QVBoxLayout(page2)
        page2_layout.addWidget(QLabel("这里是设置区域"))
        self.stacked_widget.addWidget(page2)
        
        # 添加页面3 - 关于页
        page3 = QWidget()
        page3_layout = QVBoxLayout(page3)
        page3_layout.addWidget(QLabel("这里是关于区域"))
        self.stacked_widget.addWidget(page3)
        
        # 将左右两部分添加到主布局
        main_layout.addWidget(button_frame)
        main_layout.addWidget(self.stacked_widget)
        
        # 连接按钮信号
        self.button2.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(1))
        self.button3.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(2))
        
        self.process_id = None

    def create_3d_button(self, text):
        """创建具有立体感的按钮"""
        button = QPushButton(text)
        button.setFixedSize(180, 50)
        button.setStyleSheet("""
                        QPushButton {
                            text-align: center;
                            padding: 12px 25px;
                            border: 1px solid #a0a0a0;
                            border-radius: 4px;
                            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                stop:0 #f6f7fa, stop:1 #e0e1e5);
                            font: 13px "微软雅黑";  /* 移除默认粗体 */
                            color: #505050;
                        }
                        QPushButton:checked, QPushButton:pressed {
                            font-weight: bold;  /* 仅在选中/按下时加粗 */
                        }
                        QPushButton:hover {
                            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                stop:0 #e3e7ef, stop:1 #d4d7dc);
                        }
                        QPushButton:checked {
                            background: #e3f2fd;
                            border: 1px solid #2196F3;
                            color: #1565C0;
                        }
                        QPushButton:pressed {
                            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                stop:0 #d0d0d0, stop:1 #e0e0e0);
                        }
                    """)
        return button

    def start_external_program(self):
        if self.process_id is None:
            script_dir = os.path.dirname(os.path.abspath(__file__))
            exe_path = os.path.join(script_dir, "SMA_stp05.exe")
            
            if not os.path.exists(exe_path):
                QMessageBox.critical(self, "错误", f"未找到程序: {exe_path}")
                return
                
            self.button.setEnabled(False)  # 禁用按钮防止重复点击
            self.worker_thread = WorkerThread(exe_path)
            self.worker_thread.finished_signal.connect(self.on_thread_finished)
            self.worker_thread.start()
        else:
            self.terminate_external_program()

    def on_thread_finished(self, success):
        self.button.setEnabled(True)
        if success:
            self.process_id = self.worker_thread.process.pid
            self.button.setText("停止程序")
        else:
            QMessageBox.critical(self, "错误", "启动外部程序失败")

    def terminate_external_program(self):
        if self.worker_thread and self.worker_thread.process:
            try:
                self.worker_thread.process.terminate()
                self.worker_thread.process.wait(2)
                if self.worker_thread.process.poll() is None:
                    self.worker_thread.process.kill()
            except:
                os.system(f'taskkill /f /im SMA_stp05.exe')
        self.process_id = None
        self.button.setText("启动外部程序")


class WorkerThread(QThread):
    finished_signal = pyqtSignal(bool)
    
    def __init__(self, exe_path, parent=None):
        super().__init__(parent)
        self.exe_path = exe_path
        self.process = None
        
    def run(self):
        try:
            self.process = subprocess.Popen(
                [self.exe_path],
                cwd=os.path.dirname(self.exe_path),
                creationflags=subprocess.CREATE_NEW_CONSOLE
            )
            time.sleep(1)  # 等待程序启动
            self.minimize_exe_window()
            self.finished_signal.emit(True)
        except Exception as e:
            print(f"线程执行出错: {str(e)}")
            self.finished_signal.emit(False)
            
    def minimize_exe_window(self):
        """最小化外部程序窗口"""
        if self.process:
            start_time = time.time()
            while time.time() - start_time < 5:
                try:
                    def callback(hwnd, extra):
                        if win32gui.IsWindowVisible(hwnd):
                            _, pid = win32process.GetWindowThreadProcessId(hwnd)
                            if pid == self.process.pid:
                                win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
                                return False
                        return True
                    win32gui.EnumWindows(callback, None)
                    break
                except:
                    time.sleep(0.5)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())